package cn.scw.framework.protocol.udp;

import cn.scw.common.utils.ByteUtil;
import cn.scw.framework.protocol.DataResolverManager;
import cn.scw.framework.protocol.ResolverContext;
import cn.scw.framework.protocol.SenderType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 接收数据，并将数据交由数据处理器进行处理
 */
public class UdpDataHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        private static Logger logger= LoggerFactory.getLogger(UdpDataHandler.class);

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg){

                try {
                        // 因为Netty对UDP进行了封装，所以接收到的是DatagramPacket对象。

                        ByteBuf buf = msg.content();
                        //获取内容二进制数组
                        byte[] content = getByteContent(buf);

                        logger.info(
                                "receiveddata:[host："+msg.sender().getHostString()+
                                        ",port:"+msg.sender().getPort()+
                                        ",content:"+ ByteUtil.bytesToBinaryString(content)+"]");

                        ResolverContext context = new ResolverContext();
                        context.setSenderIp(msg.sender().getAddress());
                        context.setSenderType(SenderType.UDP);
                        context.setPort(msg.sender().getPort());

                        //处理数据-
                         DataResolverManager.getInstance().resolveData(content, context);
                }catch (Exception ex){
                        logger.error(ex.getMessage()+
                                ",receiveddata:[host："+msg.sender().getHostString()+
                                ",port:"+msg.sender().getPort()+
                                ",content:"+ByteUtil.bytesToBinaryString(getByteContent(msg.content()))+"]");
                }

        }

        protected byte[] getByteContent(ByteBuf by) {
                if (by.hasArray()) {//检查是否有支持数组
                        //TODO 不确定这里的处理场景及正确性
                        byte[] array = by.array();     //得到支持数组
                        int offset = by.arrayOffset() + by.readerIndex();//计算第一个字节的偏移量
                        int length = by.readableBytes();//计算可读字节数
                        return array;
                } else {
                        int length = by.readableBytes();//得到可读字节数
                        byte[] array = new byte[length];    //分配一个具有length大小的数组
                        by.getBytes(by.readerIndex(), array); //将缓冲区中的数据拷贝到这个数组中
                        return array;
                }
        }

}
